"""
@Project :auto-phone
@File    :spider.py
@IDE     :PyCharm
@Author  :mengying
@Date    :2024/2/25 16:29
@desc    :网易云音乐爬虫
"""
import execjs
import requests
from pydub import AudioSegment

encrype_js_path = "./encrypet.js"


def m4a_to_mp3(m4a_file, mp3_file):
    audio = AudioSegment.from_file(m4a_file, format="m4a")
    audio.export(mp3_file, format="mp3")


def get_music(music_id):
    with open(encrype_js_path, "r", encoding='utf-8') as f:
        code = f.read()
    run = execjs.compile(code)
    result = run.call(
        "encryptoMusicData",
        music_id
    )
    url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token='
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67'
    }
    post_data = {
        'params': result.get('params'),
        'encSecKey': result.get('encSecKey')
    }
    res = requests.post(url=url, headers=header, data=post_data)
    result = res.json()
    print(result['data'][0]['url'])
    m4a_url = result['data'][0]['url']
    temp_path = "./temp.m4a"
    with open(temp_path, mode='wb') as f:
        f.write(requests.get(m4a_url).content)


if __name__ == '__main__':
    get_music("1831467356")
